package com.project.controller;


import com.project.common.RedisCacheManager;
import com.project.common.ServerResponse;
import com.project.dao.IpAddressMapper;
import com.project.pojo.IpAddress;
import com.project.pojo.User;
import com.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/login")
public class LoginController extends BaseController{


    @Autowired
    private RedisCacheManager redisCache;

    @Autowired
    private UserService userService;

    @RequestMapping
    public String login(){
        return "login";
    }
    @RequestMapping("/registerPage")
    public String register(){
        return "register";
    }

    @RequestMapping("/check")
    @ResponseBody
    public ServerResponse<User> checkLogin(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password=request.getParameter("password");
        ServerResponse<User> response = userService.checkLogin(username,password);
        if(response.getStatus()!=0){
            return response;
        }
        if(!redisCache.cacheUserInfo(response.getData())) {
            return ServerResponse.createByErrorMessage("登录异常,请及时联系管理员!");
        }
        return response;
    }

    @RequestMapping("/registerStu")
    @ResponseBody
    public ServerResponse<String> register(User user, HttpServletRequest request, HttpServletResponse response) {
        user.setRole(0);
        ServerResponse<String> serverResponse = userService.createUser(user);
        if(response.getStatus() == 0){
            delAllCookie(request,response);
        }
        return serverResponse;
    }

    @RequestMapping("/checkUser")
    @ResponseBody
    public ServerResponse<String> checkName(HttpServletRequest request){
        String username = request.getParameter("username");
        ServerResponse<String> response = userService.checkUser(username);
        return response;
    }

    @RequestMapping("/registerTea")
    @ResponseBody
    public ServerResponse<String> registerTea(User user,HttpServletRequest request,HttpServletResponse response) {
        user.setRole(1);
        ServerResponse<String> serverResponse = userService.createUser(user);
        if(response.getStatus() == 0){
            delAllCookie(request,response);
        }
        return serverResponse;
    }
}
